<template>
  <Dialog
      v-model="showDialog"
      title="选择分组"
      :width="500"
      @confirm="submitForm"
      @close="handleClosed"
      @open="openDialog"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="auto"
        label-position="top"
    >
      <el-form-item label="分组" prop="categoryIds">
        <tree-select
            class="tree_select"
            v-model="form.categoryIds"
            :multiple="true"
            :treeSelectData="treeSelectData"
            :treeProps="{
              label: 'categoryName'
            }"
            placeholder="请选择分组"
        ></tree-select>
      </el-form-item>
    </el-form>
  </Dialog>
</template>
<script lang="ts" setup>
import {getTaskCategoryTree, saveOrUpdateTaskInfoMultiple} from "@/api/taskCenter";
import {Ref, WritableComputedRef} from "vue";
import {ITaskCategoryItem, ITaskListItem} from "@/api/modules/taskCenter";

const props = withDefaults(defineProps<{
  show: boolean;
  selectionList: ITaskListItem[];
}>(),{});
const emits = defineEmits<{
  (e: 'update:show', val: boolean):void,
  (e: 'confirm'):void,
  (e: 'cancel'):void
}>()

const formRef = ref();
const treeSelectData:Ref<ITaskCategoryItem[]> = ref([] as any);
const form = reactive({
  categoryIds: [],
});
const rules = ref({
  categoryIds: [{required: true, message: "请选择分组", trigger: "blur"}],
});

const showDialog:WritableComputedRef<boolean> = computed({
  get() {
    return props.show
  },
  set(newValue) {
    emits("update:show", newValue)
  }
})

const openDialog = async () => {
  const rs = await getTaskCategoryTree({status: 1})
  if (rs.code === 200) {
    treeSelectData.value = rs.payload ?? [];
  }
};

const submitForm = async () => {
  await formRef.value.validate((valid: any) => {
    if (valid) {
      updateCategoryBatch();
    }
  });
};

const updateCategoryBatch = async () => {
  const data = props.selectionList.map(item => ({
    id: item.id,
    categoryIds: form.categoryIds
  }))
  const rs = await saveOrUpdateTaskInfoMultiple(data);
  if (rs.code === 200) {
    ElMessage.success(`修改成功`);
    showDialog.value = false
    confirm();
  }
};

const confirm = () => {
  emits("confirm")
};

const handleClosed = () => {
  formRef.value.resetFields();
  emits("cancel");
};

</script>
<style lang="scss" scoped>
._tree_select {
  width: 100%;
}
</style>
